package spider.impl.chapter;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import spider.NovelSiteEnum;
import spider.entitys.Chapter;
import spider.impl.AbstractSpider;
import spider.interfaces.IChapterSpider;
import spider.util.NovelSpiderUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 抓取任意网站的章节列表
 */
public class AbstractChapterSpider extends AbstractSpider implements IChapterSpider {

    @Override
    public List<Chapter> getChapter(String url) {
        try {
            String result = craw(url,"chapter-charset");
            Document doc = Jsoup.parse(result);
            doc.setBaseUri(url);
            Elements as = doc.select(NovelSpiderUtil.getContext(NovelSiteEnum.getNovelSiteEnumByUrl(url)).get("chapter-list-selector"));
            List<Chapter> chapters = new ArrayList<>();
            for(Element a : as){
                Chapter chapter = new Chapter();
                chapter.setTitle(a.text());
                chapter.setUrl(a.absUrl("href"));  //  url+a.attr("href") 这是暂时的,不是通用方法  应是设置路径
                chapters.add(chapter);
            }
            return chapters;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
